package com.gitee.core.zookeeper;

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.TimeUnit;

/**
 * Created by zhang_tao6 on 2017-11-21.
 */
public class ZooKeeperUtis {
    //提前创建好存储Seq的"/createSeq"结点 CreateMode.PERSISTENT
    public static final String SEQ_ZNODE = "/seq";

    //通过znode数据版本实现分布式seq生成
    public static class Task1 implements Runnable {

        private final String taskName;

        public Task1(String taskName) {
            this.taskName = taskName;
        }

        @Override
        public void run() {
            ZkClient zkClient = new ZkClient("10.20.42.230:2181", 3000, 10000);
            Stat stat = zkClient.writeDataReturnStat(SEQ_ZNODE, new byte[0], -1);
            int versionAsSeq = stat.getVersion();
            System.out.println(taskName + " obtain seq=" + versionAsSeq);
            zkClient.close();
        }
    }


    public static void main(String[] args) {
        ZkClient zkClient = new ZkClient("10.20.42.239:2181,10.20.42.230:2181", 3000, 10000);
        SimpleDistributedLockMutex lock = new SimpleDistributedLockMutex(zkClient, "/project","xxoo1");
        try {
//            if (!zkClient.exists("/project")) {
//                zkClient.createPersistent("/project");
//            }
            boolean hasLock = lock.acquire(5, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        if (!zkClient.exists(SEQ_ZNODE)) {
//            zkClient.createPersistent(SEQ_ZNODE);
//        }
//        //main
//        final ExecutorService service = Executors.newFixedThreadPool(20);
//
//        for (int i = 0; i < 20; i++) {
//            service.execute(new Task1("[Concurrent-" + i + "]"));
//        }
    }
}
